<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\Grid\Detail;
use App\Admin\Repositories\SalePerformance;
use App\Enums\DataPermission;
use App\Enums\OptionType;
use App\Enums\SalePerformanceType;
use App\Services\OptionService;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;

class SalePerformanceController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid(): Grid
    {
        return Grid::make(new SalePerformance(), function (Grid $grid) {
            $grid->model()
                ->with(['customer', 'user', 'payment'])
                ->when($this->getAdminDataPermission() == DataPermission::SELF, function (Builder $builder) {
                    $builder->where('user_id', self::getUserId());
                })
                ->orderByDesc('id');
            $grid->column('customer.name', trans('customer.fields.name'));
            $grid->column('customer.phone', trans('customer.fields.phone'));
            $grid->column('payment.name', trans('sale-performance.fields.payment_option_id'));
            $grid->column('user.name', trans('sale-performance.fields.user_id'));
            $grid->column('type')->display(function ($value) {
                return SalePerformanceType::getDescription($value);
            });
            $grid->column('money');
            $grid->column('pay_images')->display(function () {
                return $this->getPayImages();
            })->image('', 50, 50);
            $grid->column('disease');
            $grid->column('consultation');
            $grid->column('remark');
            $grid->column('created_at');

            $grid->disableCreateButton();
            if ($this->getAdminDataPermission() == DataPermission::SELF) {
                //个人权限，禁止删除
                $grid->disableDeleteButton();
            } else {
                $grid->showQuickEditButton();
            }

            $grid->filter(function (Grid\Filter $filter) {
                $filter->like('customer.name', trans('customer.fields.name'));
                $filter->like('customer.phone', trans('customer.fields.phone'));
                $filter->like('user.name', trans('sale-performance.fields.user_id'));
                $filter->equal('type')->select(SalePerformanceType::asSelectArray());

            });

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->append(new Detail());
            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    public function detail(int $id): Show
    {
        return Show::make($id, SalePerformance::with(['customer', 'user', 'payment']), function (Show $show) {
            $show->field('customer.name', trans('customer.fields.name'));
            $show->field('customer.phone', trans('customer.fields.phone'));
            $show->field('payment.name', trans('sale-performance.fields.payment_option_id'));

            $show->field('user.name', trans('sale-performance.fields.user_id'));
            $show->field('type')->as(function ($value) {
                return SalePerformanceType::getDescription($value);
            });
            $show->field('money');
            $show->field('pay_images')->as(function () {
                return $this->getPayImages();
            })->image();

            $show->field('medication');
            $show->field('treatment');
            $show->field('bill');
            $show->field('disease');
            $show->field('symptom');
            $show->field('consultation');
            $show->field('remark');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form(): Form
    {
        return Form::make(new SalePerformance(), function (Form $form) {
            $form->select('payment_option_id')->options(OptionService::getOption(OptionType::PAYMENT))->required();
            $form->number('money')->min(1)->max(999999)->required();
            if ($form->model()->type != SalePerformanceType::BALANCE) {
                $form->text('medication');
                $form->text('treatment');
                $form->text('bill');
                $form->text('disease')->maxLength(100);
                $form->text('symptom');
                $form->datetime('consultation');
            }
            $form->multipleImage('pay_images_str', trans('sale-performance.fields.pay_images'))->default($form->model()->getPayImages(), true)->move('images/' . date('Y') . '/' . date('m') . '/' . date('d'))->retainable()->uniqueName()->autoUpload();
            $form->hidden('pay_images');
            $form->textarea('remark');
            $form->saving(function (Form $form) {
                $form->pay_images = '';
                if (request('pay_images_str')) {
                    $images = explode(',', request('pay_images_str'));
                    foreach ($images as $key => $value) {
                        if (filter_var($value, FILTER_VALIDATE_URL) !== false) {
                            $images[$key] = Str::replace(getAliOssDomain(), '', Arr::first(explode('?', $value)));
                        }
                    }
                    $form->pay_images = json_encode($images);
                }
                $form->medication = $form->medication ?:'';
                $form->treatment = $form->treatment ?:'';
                $form->bill = $form->bill ?:'';
                $form->disease = $form->disease ?:'';
                $form->symptom = $form->symptom ?:'';
            });
            $form->ignore(['type_str', 'pay_images_str']);
        });
    }
}
